package com.whyw.system.filter;

import com.whyw.system.security.JwtUtil;
import com.whyw.system.security.MyUserDetailsService;
import com.whyw.constant.UserConstant;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@Component
public class JwtFilter extends OncePerRequestFilter {
    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private MyUserDetailsService userDetailsService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            try {
                Map<String, Object> userInfo = jwtUtil.parseJWT(token);

                String username = userInfo.get(UserConstant.USERNAME).toString();

                String data = stringRedisTemplate.opsForValue().get(UserConstant.USER_TOKEN + username);

                if (data == null) {
                    throw new RuntimeException(UserConstant.AUTH_FAILED);
                }

                UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(userDetails, null, null);

                SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            } catch (Exception e) {
                logger.error(e.getMessage());
                response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 403
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter out = response.getWriter();
                out.write(String.format("{\"code\": 0, \"msg\": \"%s\", \"data\": null}", UserConstant.AUTH_FAILED));
                out.flush();
                out.close();
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}
